

import sys
import time
from pathlib import Path
from flask import Flask, render_template, request, redirect, flash, jsonify
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'dev'  # Required for flash messages

# Database configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sensor_data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class SensorData(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(db.String(20), nullable=False)
    device_id = db.Column(db.String(50), nullable=False)
    temperature = db.Column(db.Float, nullable=False)
    humidity = db.Column(db.Float, nullable=False)

    def __repr__(self):
        return f'<SensorData {self.device_id} {self.timestamp}>'

# Create database tables
with app.app_context():
    db.create_all()

@app.route('/api/data', methods=['POST'])
def receive_data():
    data = request.json
    if not data or not all(key in data for key in ['timestamp', 'device_id', 'temperature', 'humidity']):
        return jsonify({'error': 'Invalid data format'}), 400
    
    new_record = SensorData(
        timestamp=data['timestamp'],
        device_id=data['device_id'],
        temperature=data['temperature'],
        humidity=data['humidity']
    )
    db.session.add(new_record)
    db.session.commit()
    return jsonify({'message': 'Data received successfully'}), 201

@app.route('/api/data', methods=['GET'])
def get_data():
    records = SensorData.query.order_by(SensorData.timestamp.asc()).all()
    return jsonify([{
        'timestamp': r.timestamp,
        'device_id': r.device_id,
        'temperature': float(r.temperature),
        'humidity': float(r.humidity)
    } for r in records])

@app.route('/')
def dashboard():
    return render_template('dashboard.html')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5550, debug=True)
